//引入express
const express  = require('express')
//引入解析req.body.插件
const bodyParser = require('body-parser');
//引入token
var jwt = require('./dao/jwt');

const app = express();
const port = 3000;

// app.get('/',(req,res)=>{
//   res.send('hello world!')
// })

//设置允许跨域访问服务
// app.all('*',function (req,res,next) {
//   res.header('Access-Control-Allow-Origin','*')
//   res.header('Access-Control-Allow-Headers','Content-Type');
//   res.header('Access-Control-Allow-Methods','*')
//   res.header('Content-Type','application/json;charset=utf-8');
//   next();
// });
app.all('*',function (req,res,next) {
  res.header('Access-Control-Allow-Origin','*')
  res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials',true);
  res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');
  res.header('X-Powered-By','3.2.1');
  //为了方便返回json
  res.header('Content-Type','application/json;charset=utf-8');
  if(req.method == 'OPTIONS'){
    //让options请求快速返回
    res.sendStatus(200);
  }else{
    next();
  }
});

//解析前端数据（限制文件传输大小）
app.use(bodyParser.urlencoded({limit:'50mb',extended:true}));
app.use(bodyParser.json({limit:'50mb'}));

//获取静态文件
app.use(express.static(__dirname+'/data'))

//路由守卫
app.use(function(req,res,next){
  if(typeof(req.body.token)!='undefined'){
    //处理token匹配
    let token = req.body.token
    let result = jwt.verifyToken(token);
    if(result == 1){
      //通过验证
      next();
    }else{
      //验证不通过
      res.send({status:300});
    }
  }else{
    next();
  }
});

require('./router/index')(app);
require('./router/files')(app);

//404 页面
app.use(function(req,res,next){
  let err = new Error("Not Found!");
  err.status = 404;
  next(err); 
});

//出现错误
app.use(function(err,req,res,next){
  res.status(err.status || 500);
  res.send(err.message);
});


app.listen(port, ()=>{
  console.log(`Yike app is running at port: ${port} !`)
})
